package org.smart.framework.core.util;/**
 * Created by Administrator on 2017/2/11.
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author lyric
 * @version 1.0.0
 * @date 2017/2/11 14:04
 * @description 流操作工具类
 */
public final class StreamUtil {

    private static final Logger logger = LoggerFactory.getLogger(StreamUtil.class);

    /**
     * @author lyric
     * @description 从输入流中获取字符串
     * @param is 输入流对象
     * @return
     */
    public static String getString(InputStream is) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while (null != (line = reader.readLine())) {
                sb.append(line);
            }
        } catch (IOException e) {
            logger.error("get string failure", e);
            throw new RuntimeException(e);
        }
        return sb.toString();
    }

    /**
     * @author lyric
     * @description 将输入流复制到输出流
     * @param is 输入流对象
     * @param os 输出流对象
     */
    public static void copyStream(InputStream is, OutputStream os) {
        try {
            int length;
            byte[] buffer = new byte[4 * 1024];
            while (-1 != (length = is.read(buffer, 0, buffer.length))) {
                os.write(buffer, 0, length);
            }
            os.flush();
        } catch (Exception e) {
            logger.error("copy stream failure", e);
            throw new RuntimeException(e);
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != os) {
                    os.close();
                }
            } catch (IOException e) {
                logger.error("close stream failure", e);
            }
        }
    }
}
